<template>
  <div class="select-data-container">
    <div class="select-box" >
      <el-select
        v-model="labelValue"
        v-bind="$attrs"
        :disabled="disabled || !selectAble"
        v-on="$listeners"
        contenteditable="false"
        :popper-class="'select'"
        @focus.prevent.stop="alertDialog"
        @blur.prevent.stop="alertDialog"
        style="display: block;"
        :filterable="true"
        clearable
        @remove-tag="removeTag"
        @visible-change="visibleChange"
        :allow-create="canInput"
        :default-first-option="canInput"
        onmouseover="this.title = this.getElementsByClassName('el-input__inner')[0].value"
      >
        <el-option
          v-for="o in optionsData"
          :key="o.value"
          :label="o.label"
          :value="o.value"
        >
        </el-option>
      </el-select>
      <template v-if="!disabled">
        <i
          class="icon el-icon-search active-search-icon"
          v-show="searchIconVisible"
          slot="suffix"
          @click.stop="alertDialog"
        ></i>
      </template>
    </div>
    <search-tree-dialog-type2
      :visibleValue.sync="dialogShow"
      :props="props"
      :url="url"
      :title="title"
      ref="dialog2"
      :params="params"
      :paramsMap="paramsMap"
      :options="optionsData"
      :headers="headers"
      :responseType="responseType"
      :getDictResultMap="getDictResultMap"
      :getDictSuccessStatus="getDictSuccessStatus"
      :searchKey="searchKey"
      :labelFields="labelFields"
      v-bind="$attrs"
      v-on="bindListeners"
      @dialogDataChange="dialogDataChange"
    ></search-tree-dialog-type2>
  </div>
</template>

<script>
  import searchTreeDialogType2 from './dialog/searchTreeDialogType2';
  import BaseRequestComponent from "../BaseRequestComponent";
  import arr from "../../../../utils/function/arr";
  import deepClone from "../../../../utils/function/deepClone";
  export default {
    name: "ZbFormTree",
    extends:BaseRequestComponent,
    components: {searchTreeDialogType2},
    directives: {},
    filters: {},
    mixins: [],
    props: {
      value: [Object,String, Number, Array],
      filterable: Boolean,
      maxCount:null,
      url: {
        type: String,
        default: ""
      }, // 请求地址
      canInput: {
        type: Boolean,
        default: false
      }, // 是否可以输入
      selectAble: {
        type: Boolean,
        default: true
      }, // 是否可以选择
      params: {
        type: Object,
        default: () => ({
        })
      },
      paramsMap: {
        type: Object,
        default: () => ({
        })
      },
      // 弹窗的类型
      dialogType: {
        type: Number,
        default:() =>1
      },
      options: Array, // 选项
      // 默认的props
      props: {
        type: Object,
        default: () => ({
          children: 'children',
          label: 'label',
          value: 'id',
        })
      },
      title: {
        type: String,
        default: "数据选择"
      },
      disabled: Boolean,
      dataField: String, // 返回结果中显示的字段名
      labelText: [String, Number, Array], // 无下拉选项时显示的名称
      // 下拉选项显示字段
      labelFields: {
        type: Array,
        default: () => []
      },
      searchAbel: Boolean, // 开启搜索
      searchKey: {
        // 查询请求的key
        default: "nameOrNumber"
      },
      searchIconVisible: {
        // 显示搜索图标
        type: Boolean,
        default: false
      },
      searchDialogEnable: {
        // 是否开启显示搜索框
        type: Boolean,
        default: true
      },
      autoFirst: {
        // 是否自动选择第一个
        type: Boolean,
        default: false
      },
      asyncLoad: {
        // 是否是同步加载数据 同步为 true（当列表有多个该组件渲染时，只会加载一次） 异步为 false
        type: Boolean,
        default: false
      },
      dynamicLableText:[String, Number, Array],
    },
    data() {
      return {
        optionsData: [],
        labelValue: "",
        dialogShow: false
      };
    },
    computed: {
      bindListeners() {
        const events = this.$attrs.listeners
        return Object.assign(this.$listeners,events)
      },
    },
    watch: {
      value: {
        handler(val) {
          this.labelValue = val
        },
        immediate: true
      },
      url: {
        handler(val) {
          if (this.createdRequest){
          }
        },
        immediate: true
      },
      params: {
        handler(val, oldVal) {
          if (val !== oldVal) {
            if (this.createdRequest){
            }
          }
        },
        deep: true
      },
    },
    methods: {
      // 弹出选择框
      alertDialog() {
        if (!this.searchDialogEnable) return;
        if (!this.disabled) {
          this.$attrs.value = this.value
          this.dialogShow = true;
        }
      },
      // 移除 事件 返回选中的对象
      removeTag(val) {
        let dialog2 = this.$refs.dialog2;
        if (dialog2.checkedValues && dialog2.checkedValues.length){
          dialog2.checkedValues = dialog2.checkedValues.filter(item=>item[dialog2.props.value]!==val)
        }
        if (dialog2.checkedValuesId && dialog2.checkedValuesId.length){
          dialog2.checkedValuesId = dialog2.checkedValuesId.filter(item=>item!==val)
        }
        console.log('获取的所有的选项',dialog2.checkedValues)
        console.log('获取的所有的选中的数据',dialog2.checkedValuesId)
      },
      visibleChange(e){
        this.$nextTick(function () {
          let elementsByClassName = document.getElementsByClassName("el-select-dropdown");
          if (elementsByClassName && elementsByClassName.length){
            for (let i = 0; i < elementsByClassName.length; i++) {
              elementsByClassName[i].setAttribute("style", "display:none")
            }
          }
        })
      },
      // dataChange 事件 返回选中的对象
      dataChange(val) {
        if (this.maxCount && val.length > this.maxCount){
          val.pop()
          return this.$message.info(`最多只能选择${this.maxCount}项`)
        }
        if(val instanceof Array && val.length){
          let valValue = arr(val).pluck(this.props.value).all()
          let valLabel = arr(val).pluck(this.props.label).all()
          this.$emit( "dataChange",val,valValue,valLabel);
        }else{
          this.$emit( "dataChange",val,val[this.props.value],val[this.props.label]);
        }
      },
      // change事件
      dialogDataChange(data) {
        const { value } = this.props;
        if (this.$attrs.multiple && data && data instanceof Array) {
          this.labelValue = data.map(item=>item[value])
          this.value = this.labelValue
          this.optionsData =  arr(data).transform((item)=>{
            return {value:item[this.props.value],label:item[this.props.label]}
          }).all()
          console.log('传递的值',this.labelValue)
          console.log('生成的选项',this.optionsData)
          this.$emit("input", this.labelValue);
          this.$emit("change", this.labelValue);
          this.dataChange(data)
        }else{
          this.labelValue = data[value]
          this.value = this.labelValue
          this.optionsData =  [
            {value:this.labelValue,label:data[this.props.label]},
          ]
          console.log('传递的值',this.labelValue)
          console.log('生成的选项',this.optionsData)
          this.$emit("input", this.labelValue);
          this.$emit("change", this.labelValue);
          this.dataChange(data)
        }
      },
    }
  };
</script>

<style scoped lang="scss">
  .active-search-icon{
    color: #1890ff !important;
    font-weight: bold;
  }
  .active-search-icon :hover{
    color: #1890ff22 !important;
    font-weight: bold;
  }
  .select-data-container {
    position: relative;
    /deep/ .el-input {
      &:hover {
        cursor: pointer;
      }
      input {
        &:hover {
          cursor: pointer;
        }
      }
    }
    .select-box {
      position: relative;
      .icon {
        cursor: pointer;
        color: #c0c4cc;
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    /deep/ .el-select {
      width: 100%;
      height: 100%;
      display: block;
      position: relative;
      .el-input__suffix {
        display: none;
        .el-icon-arrow-up {
          display: none;
        }
      }
      &:hover .el-input__suffix {
        display: inline;
        margin-right: 16px;
      }
    }
    /deep/ .is-disabled .el-input__inner {
      color: #4d4d4d;
    }


  }
  .select-tree {
    display: none;
  }
  ::v-deep.el-select-dropdown__list{
    display: none !important;
  }
  >>> .el-select-dropdown__list {
    display: none !important;
  }
</style>
